package com.unziper.helpapp.tapestry.pages;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.upload.services.UploadedFile;

import com.unziper.helpapp.util.DisplayManager;
import com.unziper.helpapp.util.IUnZiper;
import com.unziper.helpapp.util.IUploadManager;
import com.unziper.helpapp.util.UnZiper;
import com.unziper.helpapp.util.UploadManager;

/**
 * Start page of application helpapp.
 */
public class Index {

	@Property
	private UploadedFile file;

	@Persist
	private IUnZiper unZiper;

	@Persist
	private IUploadManager uploadManager;

	@SetupRender
	public void initialize() {
		if (unZiper == null) {
			unZiper = new UnZiper();
		}
		if (uploadManager == null) {
			uploadManager = new UploadManager();
		}
	}

	@Property
	private String currentFilePath;

	public List<String> fileList() {
		if (unZiper.isUnziped()) {
			File outFile = new File(UnZiper.OUTPUT_FOLDER);
			List<String> result = DisplayManager.getFilesPaths(outFile);
			return result;
		}
		return new ArrayList<String>();
	}
	
	public boolean containsFilesData() {
		if (fileList().isEmpty()) {
			return false;
		}
		return true;
	}

	public Object onSuccess() {
		uploadManager.saveToFile(file.getStream(), file.getFileName());

		// Unzip all uploaded zip files. Support for multi-uplaod. Currently is
		// single upload.
		for (String currentFileName : uploadManager.getZipFileNames()) {
			unZiper.unzip(new File(IUploadManager.OUTPUT_DIRECTORY + File.separator
					+ currentFileName));
		}
		return null;
	}
}
